package cn.com.xy.sms.sdk.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import cn.com.xy.sms.sdk.db.entity.ContactsColumns;

/**
 * @author Jinjia
 *  
 *  通讯录数据库助手
 */
public class ContactsDBHelper extends SQLiteOpenHelper {
	
	private static final String DB_NAME = "duoqu_contacts.db";
	/*SDK-637 zhaojiangwei 20160929 start*/
	private static final int VERSION = 5;
	/*SDK-637 zhaojiangwei 20160929 end*/
	/**
	 * 创建联系人表的 SQL 语句
	 */
	private static final String CREATE_CONTACTS_SQL =
			"CREATE TABLE IF NOT EXISTS "
			+ ContactsColumns.TABLE_NAME + "("
			+ ContactsColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
			+ ContactsColumns.PHONE + " TEXT, "
			+ ContactsColumns.NAME + " TEXT, "
			+ ContactsColumns.DATA + " TEXT, "
			+ ContactsColumns.UPDATE_TIME + " TEXT)";
	
	
	public ContactsDBHelper(Context context) {
		super(context, DB_NAME, null, VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(CREATE_CONTACTS_SQL);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}
	
	/**
	 * 判断是否存在某个表 SQL 语句
	 */
	private String SQL_IS_EXIST_TABLE = "SELECT COUNT(*) AS c FROM sqlite_master WHERE type ='table' AND name =?";
	
	/**
	 * 是否存在某个表
	 * 
	 * @param tableName 表名
	 * @return 是否存在
	 */
	public boolean isExistTable(String tableName) {
	    if (TextUtils.isEmpty(tableName)) {
	        return false;
	    }

	    boolean exist = false;
	    Cursor cursor = getReadableDatabase().rawQuery(SQL_IS_EXIST_TABLE, new String[] { tableName });
	    if (cursor.moveToNext()) {
	        exist = cursor.getInt(0) > 0;
	    }
	    cursor.close();
	    
        return exist;
	}

}
